import { Module } from "vuex";
import { Goods } from "@/entity/Goods";
import { getCartList } from "@/api/cart";

export interface CartState {
  cartList: Goods[];
}

/**
 * 如果设置了 namespaced 属性前就要加上 cart/
 */
export interface CartGetters {
  // 商品类型总数
  "cart/typeCount": number;
  // 商品总数
  "cart/count": number;
}

export interface CartMutations {
  // 设置购物车
  "cart/SetCartList": Goods[];
  // 增加购物车
  "cart/AddCartList": Goods;
  // 减少购物车
  "cart/reduceCartList": Goods;
  // 删除购物车
  "cart/removeCartList": Goods;
}

export interface CartActions {
  // 获取购物车
  "cart/getCartList": {
    payload: Parameters<typeof getCartList>[0];
    promise: Goods[];
  };
}

const cart: Module<CartState> = {
  namespaced: true,
  state: {
    cartList: [],
  },
  getters: {
    // 商品类型总数
    typeCount: (state) => state.cartList.length,
    // 商品总数
    count: (state) =>
      state.cartList.reduce((prev, current) => prev + current.number, 0),
  },
  mutations: {
    // 设置购物车
    SetCartList(state, list: Goods[] = []) {
      state.cartList = [...list];
    },
    // 增加购物车
    AddCartList(state, goods: Goods) {
      goods = Object.assign({}, goods);

      const findGoods = state.cartList.find(
        (item) => item.goodsId === goods.goodsId
      );

      if (findGoods) {
        findGoods.number++;
      } else {
        goods.number = goods.number > 1 ? goods.number : 1;
        state.cartList.push(goods);
      }
    },
    // 减少购物车
    reduceCartList(state, goods: Goods) {
      const findGoodsIndex = state.cartList.findIndex(
        (item) => item.goodsId === goods.goodsId
      );
      const findGoods = state.cartList[findGoodsIndex];

      if (findGoods) {
        if (findGoods.number > 1) {
          // 如果数量大于 1 就减少
          findGoods.number--;
        } else {
          // 数量小于等于 1 就删除
          state.cartList.splice(findGoodsIndex, 1);
        }
      }
    },
    // 删除购物车
    removeCartList(state, goods: Goods) {
      const findGoodsIndex = state.cartList.findIndex(
        (item) => item.goodsId === goods.goodsId
      );
      if (findGoodsIndex >= 0) {
        state.cartList.splice(findGoodsIndex, 1);
      }
    },
  },
  actions: {
    // 获取购物车
    getCartList({ state, commit }, ...args: Parameters<typeof getCartList>) {
      return getCartList(...args).then((res) => {
        if (!state.cartList.length) {
          commit("SetCartList", res);
        }
      });
    },
  },
};

export default cart;
